package licode.unisop.types.event.impl;

import licode.unisop.types.event.DomainEvent;
import licode.unisop.types.event.DomainEventPublish;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

/**
 * 事件发布
 *
 * @author licode
 */
@Component
public class DomainEventPublishImpl implements DomainEventPublish {
    @Resource
    private EventStoreDefault eventStoreDefault;

    private final ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();

    @PostConstruct
    public void init() {
        int cores = Runtime.getRuntime().availableProcessors();
        cores = Math.max(1, cores / 2);
        executor.setPoolSize(cores);
        executor.setThreadNamePrefix("event_executor_");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
    }

    @Override
    public <T extends DomainEvent> void publish(T event) {
        executor.schedule(() -> eventStoreDefault.publish(event),
                new Date(System.currentTimeMillis() + 100));
    }
}
